package org.fnzn.web.rest;
import org.apache.commons.lang3.StringUtils;
import org.fnzn.bean.Element;
import org.fnzn.bean.LrdRolefunc;
import org.fnzn.biz.ElementBiz;
import org.fnzn.core.Result;
import org.fnzn.service.LrdRoleFuncService;
import org.fnzn.util.ResultGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.fnzn.bean.Menu;
import org.fnzn.bean.vo.User;
import org.fnzn.biz.MenuBiz;
import org.fnzn.core.CommonConstant;
import org.fnzn.tree.AuthorityMenuTree;
import org.fnzn.tree.MenuTree;
import org.fnzn.util.TreeUtil;
import org.fnzn.web.rest.base.BaseController;

import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("menu")
public class MenuController extends BaseController<MenuBiz, Menu> {
    @Autowired
    private ElementBiz elementBiz;
    @Autowired
    private LrdRoleFuncService roleFuncService;
    /**
     * 以树的方式获取菜单列表
     * @param title
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result list(String title) {
        Example example = new Example(Menu.class);
        if (StringUtils.isNotBlank(title)){
            example.createCriteria().andLike("title", "%" + title + "%");
        }
        List<Menu> menus = baseBiz.selectByExample(example);
        List<MenuTree> trees = new ArrayList<>();
        MenuTree node = null;
        for (Menu m : menus) {
            node = new MenuTree();
            BeanUtils.copyProperties(m, node);
            trees.add(node);
        }
        trees = TreeUtil.buildByRecursive(trees, -1);
        return ResultGenerator.genSuccessResult(trees);
    }

    @RequestMapping(value = "/tree", method = RequestMethod.GET)
    public Result tree(String roleCd) {
        Example example = new Example(Menu.class);
        List<Menu> menus = baseBiz.selectByExample(example);
        List<Element> elements =  elementBiz.selectByExample(new Example(Element.class));
        List<MenuTree> rootTrees = new ArrayList<>();
        List<MenuTree> leafTrees = new ArrayList<>();
        MenuTree node = null;
        /**重新构建菜单树**/
        for (Menu m : menus) {
            node = new MenuTree();
            BeanUtils.copyProperties(m, node);
            node.setType("menu");
            rootTrees.add(node);
        }
        /**重新构建功能树**/
        for(Element ele: elements){
            node = new MenuTree();
            node.setCode(ele.getCode());
            node.setHref(ele.getUri());
            node.setTitle(ele.getName());
            node.setId(ele.getId());
            node.setParentId(Integer.valueOf(ele.getMenuId()));
            node.setType("button");
            leafTrees.add(node);
        }
        /**查找选择的功能项**/
        List<Integer> lrdRoleFunc = roleFuncService.selectIdsByRoleCd(roleCd);
        /**生成树**/
        List<MenuTree> menuTrees = TreeUtil.leafBuildTree(rootTrees, -1, leafTrees);
//        trees = TreeUtil.buildByRecursive(trees, -1);
        /**结果集组合**/
        Map<String,Object> result  = new HashMap<>();
        result.put("all",menuTrees);
        result.put("selected",lrdRoleFunc);
        return ResultGenerator.genSuccessResult(result);
    }
    /**
     * 获取所有菜单
     * @return
     */
    @RequestMapping(value = "/system", method = RequestMethod.GET)
    public List<Menu> getSystem() {
        Menu menu = new Menu();
        menu.setParentId(CommonConstant.ROOT);
        return baseBiz.selectList(menu);
    }
    /**
     * 查询当前系统菜单下所有子菜单
     * @param parentId 父菜单ID
     * @return
     */
    @RequestMapping(value = "/menuTree", method = RequestMethod.GET)
    public List<MenuTree> listMenu(Integer parentId) {
        try {
            if (parentId == null) {
                parentId = this.getSystem().get(0).getId();
            }
        } catch (Exception e) {
            return new ArrayList<MenuTree>();
        }
        List<MenuTree> trees = new ArrayList<MenuTree>();
        MenuTree node = null;
        Example example = new Example(Menu.class);
        Menu parent = baseBiz.selectById(parentId);
        example.createCriteria().andLike("path", parent.getPath() + "%").andNotEqualTo("id",parent.getId());
        return getMenuTree(baseBiz.selectByExample(example), parent.getId());
    }

    @RequestMapping(value = "/authorityTree", method = RequestMethod.GET)
    public List<AuthorityMenuTree> listAuthorityMenu() {
        List<AuthorityMenuTree> trees = new ArrayList<AuthorityMenuTree>();
        AuthorityMenuTree node = null;
        for (Menu menu : baseBiz.selectListAll()) {
            node = new AuthorityMenuTree();
            node.setText(menu.getTitle());
            BeanUtils.copyProperties(menu, node);
            trees.add(node);
        }
        return TreeUtil.bulid(trees,CommonConstant.ROOT);
    }

    @RequestMapping(value = "/user/authorityTree", method = RequestMethod.GET)
    public Result listUserAuthorityMenu(Integer parentId,HttpSession session){
    	User user = (User) session.getAttribute("user");
    	String userId = user.getUser_id();
        try {
            if (parentId == null) {
                parentId = this.getSystem().get(0).getId();
            }
        } catch (Exception e) {
            return ResultGenerator.genSuccessResult(new ArrayList<MenuTree>()) ;
        }
        List<MenuTree> trees = getMenuTree(baseBiz.getUserAuthorityMenuByUserId(userId),CommonConstant.ROOT);
        return ResultGenerator.genSuccessResult(trees);
    }

    @RequestMapping(value = "/user/system", method = RequestMethod.GET)
    public List<Menu> listUserAuthoritySystem(HttpSession session) {
        //int userId = userBiz.getUserByUsername(getCurrentUserName()).getId();
    	User user = (User) session.getAttribute("user");
    	String userId = user.getUser_id();
        return baseBiz.getUserAuthoritySystemByUserId(userId);
    }

    private List<MenuTree> getMenuTree(List<Menu> menus,int root) {
        List<MenuTree> trees = new ArrayList<MenuTree>();
        MenuTree node = null;
        for (Menu menu : menus) {
            node = new MenuTree();
            BeanUtils.copyProperties(menu, node);
            node.setComponent(menu.getPath());
            trees.add(node);
        }
        return TreeUtil.buildByRecursive(trees,root) ;
    }


}
